package org.common.utils.fasttest;

import java.math.BigInteger;

/**
 * @author zhouzhibing
 * @date 2024/10/21
 */
public class TestNumberMerge {

    private static final long MASK = 0xFFFFFFFFFFFFL;
    private static final int BITS = 64;

    public static void test() {
//        baiDuTest();
        douBaoTest();
    }

    public static void baiDuTest() {
        long a = 1234567890123456789L;
        long b = 2345678901234567890L;
        long c = 3456789012345678901L;

        long merged = merge(a, b, c);
        System.out.println("Merged: " + merged);

        long[] split = split(merged);
        System.out.println("Split: a = " + split[0] + ", b = " + split[1] + ", c = " + split[2]);
    }

    public static long merge(long a, long b, long c) {
        return (a << (2 * BITS)) | (b << BITS) | c;
    }

    public static long[] split(long merged) {
        long a = merged >> (2 * BITS);
        long b = (merged << 64) >>> (2 * BITS);
        long c = merged & MASK;
        return new long[]{a, b, c};
    }


    public static BigInteger combine(long num1, long num2, long num3) {
        return new BigInteger(String.valueOf(num1)).shiftLeft(128).or(new BigInteger(String.valueOf(num2)).shiftLeft(64)).or(BigInteger.valueOf(num3));
    }

    public static long[] extract(BigInteger combined) {
        long num1 = combined.shiftRight(128).longValue();
        long num2 = combined.shiftRight(64).and(new BigInteger("ffffffffffffffff", 16)).longValue();
        long num3 = combined.and(new BigInteger("ffffffffffffffff", 16)).longValue();
        return new long[]{num1, num2, num3};
    }


//    public static long combine(long num1, long num2, long num3) {
//        return ((num1 & 0xFFFFFFFFL) << 48) | ((num2 & 0xFFFFFFFFL) << 32) | (num3 & 0xFFFFFFFFL);
//    }

//    public static long[] extract(long combined) {
//        long num1 = combined >>> 48;
//        long num2 = (combined >>> 32) & 0xFFFFFFFFL;
//        long num3 = combined & 0xFFFFFFFFL;
//        return new long[]{num1, num2, num3};
//    }


    public static void douBaoTest() {
        long num1 = 1234567890123L;
        long num2 = 9876543210987L;
        long num3 = 555555555555L;
//        Combined: 420101683775643526971285977328622224426871448209635
//        Extracted: 1234567890123, 9876543210987, 555555555555


        BigInteger combined = combine(num1, num2, num3);
        System.out.println("Combined: " + combined);

        long[] extracted = extract(combined);
        System.out.println("Extracted: " + extracted[0] + ", " + extracted[1] + ", " + extracted[2]);
    }

}
